package cn.lyx.xiaohoshu.gateway.filter;

import cn.dev33.satoken.stp.StpUtil;
import cn.lyx.framework.common.constant.GlobalConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Author by lyx
 * 转发请求时，将用户 ID 添加到 Header 请求头中，透传给下游服务
 * @Order(-100) @Order 数值越小，过滤器的执行顺序越靠前（优先执行）。
 * public class SaReactorFilter implements SaFilter, WebFilter
 */
@Slf4j
@Component
public class AddUserId2HeaderFilter implements GlobalFilter {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("==> AddUserId2HeaderFilter.filter(), 将用户 ID 添加到 Header 请求头中");
        long userLoginId = StpUtil.getLoginIdAsLong();
        log.info("==> 当前登录的用户 ID: {}", userLoginId);
        ServerWebExchange.Builder request = exchange.mutate().request(req -> req.header(GlobalConstants.USER_ID,
                String.valueOf(userLoginId)));
        return chain.filter(request.build());
    }
}
